﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using ECS.DAL.Entity;
using ECS.DAL.Component;
using ECS.BLL.Entity;
using ECS.BLL.Component;
using ECS.Framework.ReportCR;
using ECS.Framework;
using System.Text.RegularExpressions;
using ECS.DAL;
using System.Data.Common;
namespace E_ICS.Main
{
    public partial class frmMain2 : Form
    {
        #region callotherform
        E_ICS.About h = new E_ICS.About();
        E_ICS.frmWeightSlipDisplay wsd = new E_ICS.frmWeightSlipDisplay(null);
        E_ICS.frmWHInventory wi = new E_ICS.frmWHInventory(null);
        E_ICS.frmTransactionHistory th = new E_ICS.frmTransactionHistory();
        E_ICS.frmPreManifest pm = new E_ICS.frmPreManifest();
        E_ICS.frmStattionSetup2 ss = new E_ICS.frmStattionSetup2();
        Master.frmZone z = new Master.frmZone();
        Master.frmLocation l = new Master.frmLocation();
        Master.frmZoneLocation zl = new Master.frmZoneLocation();


        #endregion
        #region private members
        int weighting;
        int sumG = 0;
        double sumN = 0;
        double sumT = 0;
        double sumP = 0;
        int sumPiecs = 0;
        //int sumW = 0;
        string mawbid = "";
        string slipid = "";
        string type = "";
        string partialflag = "";
        string ewsflag = "";
        int seq = 1;
        DataSet dataset = null;
        string appId = string.Empty;
        string device = string.Empty;
        //string stationID = string.Empty;
        string connString = string.Empty;
        SqlConnection sqlCon = null;
        string reg = @"^[A-Za-z0-9\b\cC\cV\cX]*$";

        #endregion

        #region form event

        public frmMain2()
        {
            InitializeComponent();
        }
        private void txtFltNo_TextChanged(object sender, EventArgs e)
        {
            if (txtFltNo.Text.Equals(String.Empty))
            {
                btnShowHistory.Enabled = false;
            }
            else
            {
                btnShowHistory.Enabled = true;
            }
        }
        private void txtPieces_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
            {
                //
            }
            else
            {
                //CommonMessageBox.ShowMessageError("Please insert digit only");
                e.Handled = true;

            }
        }

        private void txtSerial_TextChanged(object sender, EventArgs e)
        {
            if (txtSerial.Text.Length == 8)
            {
                if (txtHAWB.Enabled)
                {
                    txtHAWB.Focus();
                }
                else
                {
                    //btnMAWBSearch.Focus();
                    btnMAWBAdd.Focus();
                }
            }
        }


        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                appId = ConfigurationManager.AppSettings["appID"];
                device = GlobalVariable.Device;
                connString = ConfigurationManager.ConnectionStrings["con3"].ConnectionString;
                sqlCon = new SqlConnection(connString);

                btnMAWBSearch.Enabled = false;
                this.toolStripStatusLabel2.Text = GlobalVariable.userName;
                dgvWeight_Disp.RowHeadersWidth = 100;
                dgvDim.RowHeadersWidth = 100;
                dgvOthInfo.RowHeadersWidth = 85;
                lblScaleID.Text = GlobalVariable.scaleID;
                txtPrefix.Focus();

                SetMenuAuthorize();

                CommonResourceString.LoadResource(GlobalVariable.user.ApplicationID, GlobalVariable.user.Locale, GlobalVariable.Device, GlobalVariable.user.UserID);
                //if (!checkStation())
                //{
                //    btnMAWBAdd.Enabled = false;
                //}
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }

        }
        private void frmMain2_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void txtMAWB_TextChanged(object sender, EventArgs e)
        {
            if (txtPrefix.Text == "" && txtSerial.Text == "")
            {
                btnMAWBSearch.Enabled = false;
            }
            else
            {
                btnMAWBSearch.Enabled = true;
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            SlipInfoComponent slip = new SlipInfoComponent();
            ReportModule reportModule = null;
            try
            {
                reportModule = new ReportModule();
                reportModule.InitialReport(@"Report/Slip.rpt");
                ReportCriteria param = new ReportCriteria();
                param.Hawb = txtHAWB.Text;  //""; // "HP1500798";  //"NTH77037004"; // txtHAWB.Text;
                param.SlipNo = txtSlipNO.Text;  //"15-00042"; // "15-00059"; // txtSlipNO.Text;  //"15-00001"; //
                param.MawbPrefix = txtPrefix.Text;  //"235"; // "910"; // "615";// txtPrefix.Text;
                param.MawbSN = txtSerial.Text;  //"48138591"; // "09606553"; // "74120675"; // txtSerial.Text;
                param.ScaleId = lblScaleID.Text; // "09"; // "05"; // "08";
                reportModule.LoadReportData(slip.GetSlipInfo(param));
                reportModule.PrintWeightSlipTextOnly();
                //reportModule.Print();
                //ReportDialog dialog = new ReportDialog();
                //dialog.WindowState = FormWindowState.Maximized;
                //dialog.ShowReport(ref reportModule);
                //dialog.ShowDialog();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
            finally
            {
                reportModule.Dispose();
            }
        }
        private void txtPrefix_TextChanged(object sender, EventArgs e)
        {

            if (txtPrefix.Text == "" && txtSerial.Text == "")
            {
                btnMAWBSearch.Enabled = false;
            }
            else
            {
                btnMAWBSearch.Enabled = true;
            }
            if (txtPrefix.Text.Length == 3)
            {
                txtSerial.Focus();
            }
        }
        string input = string.Empty;
        private void txtPrefix_KeyPress(object sender, KeyPressEventArgs e)
        {
            //  MessageBox.Show(Keys.KeyCode.ToString());
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
            {
                Console.WriteLine(e.KeyChar);
            }
            //else if (Keys.Control == Keys.KeyCode.)
            //{

            //}
            else
            {
                //CommonMessageBox.ShowMessageError("Please insert digit only");
                if (!char.IsControl(e.KeyChar))
                {
                    e.Handled = true;
                }
            }
            //if (e.KeyChar == Convert.ToChar(13))
            //{
            //    string Pre_mawb = "";
            //    string Serial = "";
            //    Pre_mawb = input.Substring(0, 3);
            //    Serial = input.Substring(3);
            //    txtPrefix.Text = Pre_mawb;
            //    txtSerial.Text = Serial;
            //    input = "";
            //}
            //else
            //{
            //    input += e.KeyChar;
            //}

        }

        private void stationToolStripMenuItem_Click(object sender, EventArgs e)
        {

            try
            {
                E_ICS.frmStattionSetup2 ss = new E_ICS.frmStattionSetup2();
                ss.ShowDialog();
                //if (ss.Visible)
                //{
                //    // wsd.Show();
                //}
                //else
                //{
                //    if (ss.IsDisposed == true)
                //    {
                //        ss = new E_ICS.frmStattionSetup2();
                //        ss.Show();
                //    }
                //    else
                //    {
                //        ss.Show();
                //    }

                //}
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void zoneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Master.frmZone z = new Master.frmZone();
                z.ShowDialog();
                //if (z.Visible)
                //{
                //    // wsd.Show();
                //}
                //else
                //{
                //    if (z.IsDisposed == true)
                //    {
                //        z = new Master.frmZone();
                //        ss.Show();
                //    }
                //    else
                //    {
                //        z.Show();
                //    }

                //}
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }

        }

        private void locationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Master.frmLocation l = new Master.frmLocation();
                l.ShowDialog();
                //if (l.Visible)
                //{
                //    // wsd.Show();
                //}
                //else
                //{
                //    if (l.IsDisposed == true)
                //    {
                //        l = new Master.frmLocation();
                //        l.Show();
                //    }
                //    else
                //    {
                //        l.Show();
                //    }

                //}
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }

        }

        private void zoneLocationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Master.frmZoneLocation zl = new Master.frmZoneLocation();
                zl.ShowDialog();
                //if (zl.Visible)
                //{
                //    // wsd.Show();
                //}
                //else
                //{
                //    if (zl.IsDisposed == true)
                //    {
                //        zl = new Master.frmZoneLocation();
                //        zl.Show();
                //    }
                //    else
                //    {
                //        zl.Show();
                //    }

                //}
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }

        }

        private void txtSerial_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
                {
                    Console.WriteLine(e.KeyChar);
                }
                //else if (Keys.Control == Keys.KeyCode.)
                //{

        //}
                else
                {
                    //CommonMessageBox.ShowMessageError("Please insert digit only");
                    if (!char.IsControl(e.KeyChar))
                    {
                        e.Handled = true;
                    }
                }
                if (e.KeyChar == Convert.ToChar(13))
                {
                    try
                    {
                        btnMAWBSearch.Enabled = true;
                        if (ValidateMawb())
                        {
                            MAWBSearch_Click();
                        }
                        else
                        {
                            //CommonMessageBox.ShowMessageWarning("Invalid MAWB Check Digit");
                            CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Digit"));

                        }
                    }
                    catch (Exception ex)
                    {

                        // CommonMessageBox.ShowMessageError(ex);
                    }
                }
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            ValueTofrmAddMAWB.consol = true;
        }
        private void Logout()
        {
            string appId = ConfigurationManager.AppSettings["appID"];
            //string device = ConfigurationManager.AppSettings["device"];
            string device = GlobalVariable.Device;
            string ClearUserFlag = ConfigurationManager.AppSettings["userflag"];
            //string appVersion = ConfigurationManager.AppSettings["version"];
            string appVersion = GlobalVariable.version;
            try
            {
                UserAuthenticateComponent authen1 = new UserAuthenticateComponent();
                UserAuthenticate user1 = authen1.Logout(GlobalVariable.userName, appId, device);
                if (user1.Status.Equals("PASS"))
                {
                    this.Close();
                }
                else
                {
                    //CommonMessageBox.ShowMessageInfo(user1.Message);
                }
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }
        }
        #endregion

        #region User Authorization
        /// <summary>
        /// 
        /// </summary>
        private void SetMenuAuthorize()
        {
            AuthorizationManager manager = new AuthorizationManager();
            manager.GetUserAuthorization(GlobalVariable.user.UserID, GlobalVariable.user.ApplicationID, GlobalVariable.user.Device,
                "EICS", 1033);
            acceptCargoToolStripMenuItem.Visible = manager.IsValidAuthorization("Accept Cargo");
            weightSlipDisplayToolStripMenuItem.Visible = manager.IsValidAuthorization("Weight Slip Display");
            WHInventoryToolStripMenuItem.Visible = manager.IsValidAuthorization("WH Inventory");
            preManifestToolStripMenuItem.Visible = manager.IsValidAuthorization("Pre Manifest Report");
            transactionHistoryToolStripMenuItem.Visible = manager.IsValidAuthorization("Transaction History");
            setupToolStripMenuItem.Visible = manager.IsValidAuthorization("Setup");
        }
        #endregion

        #region weightScale
        private void btnAddWeight_Click(object sender, EventArgs e)
        {
            //Weighting = Weighting + 1;
            //textBox10.Text = Weighting.ToString();
            Weight w = new Weight(this);
            w.ShowDialog();
        }
        private void setRowNumber(DataGridView dgv)
        {
            // dgvWeight_Disp.
            //dgv.RowHeadersWidth = 100;
            //dgvWeight_Disp.Columns[-1].HeaderText = "No";

            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (row.Index == dgv.Rows.Count - 1)
                {
                    row.HeaderCell.Value = "";
                }
                else
                {
                    row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
                }
            }
        }
        public void GetDataFromWeightDisplay(string[] items)
        {
            //No = dgvWeight_Disp.NewRowIndex + 1;
            dgvWeight_Disp.Rows.Add(String.Format("{0:#,##0}", double.Parse(items[0])), String.Format("{0:#,##0}", double.Parse(items[1])), items[2], items[3], items[4]);
            // row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
            setRowNumber(dgvWeight_Disp);
            setWeighing(dgvWeight_Disp);
            sumP = double.Parse(items[0]) + sumP;
            txtTotalPallet.Text = String.Format("{0:#,##0}", sumP);
            sumG = int.Parse(items[1]) + sumG;
            txtTotalGross.Text = sumG.ToString("##,#");

            sumT = double.Parse(String.Format("{0:n0}", double.Parse(items[2]))) + sumT;
            txtTotalTare.Text = String.Format("{0:#,##0}", sumT);
            sumN = double.Parse(String.Format("{0:n0}", double.Parse(items[3]))) + sumN;
            txtTotalNet.Text = String.Format("{0:#,##0}", sumN);


        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string tempGross = string.Empty;
            string tempTare = string.Empty;
            string tempNet = string.Empty;
            string tempPallet = string.Empty;
            string tempWeighting = string.Empty;
            try
            {

                tempPallet = String.Format("{0:##0}", Convert.ToDouble(dgvWeight_Disp.Rows[e.RowIndex].Cells[0].Value));
                tempGross = String.Format("{0:##0}", Convert.ToDouble(dgvWeight_Disp.Rows[e.RowIndex].Cells[1].Value));
                tempTare = String.Format("{0:##0}", Convert.ToDouble(dgvWeight_Disp.Rows[e.RowIndex].Cells[2].Value));
                tempNet = String.Format("{0:##0}", Convert.ToDouble(dgvWeight_Disp.Rows[e.RowIndex].Cells[3].Value));
                tempWeighting = txtWeighing.Text;
                if (e.ColumnIndex == dgvWeight_Disp.Columns["Column7"].Index && e.RowIndex >= 0)
                {
                    //var result = MessageBox.Show("Are you sure you want to Delete line ?", "Delete?", MessageBoxButtons.YesNo);
                    if (CommonMessageBox.ShowMessageConfirmYN("Are you sure you want to Delete this line ?") == DialogResult.Yes)
                    {
                        dgvWeight_Disp.Rows.RemoveAt(e.RowIndex);
                        setRowNumber(dgvWeight_Disp);
                        if (e.RowIndex == 0)
                        {
                            txtWeighing.Text = "0";
                        }
                        else
                        {
                            setWeighing(dgvWeight_Disp);
                        }

                        // No = e.RowIndex;
                        if (sumG > int.Parse(tempGross))
                        {
                            sumG = sumG - int.Parse(tempGross);
                            txtTotalGross.Text = String.Format("{0:#,##0}", sumG);
                        }
                        else
                        {
                            sumG = int.Parse(tempGross) - sumG;
                            txtTotalGross.Text = String.Format("{0:#,##0}", sumG);
                        }
                        if (sumT > int.Parse(tempTare))
                        {
                            sumT = sumT - int.Parse(tempTare);
                            txtTotalTare.Text = String.Format("{0:#,##0}", sumT);
                        }
                        else
                        {
                            sumT = int.Parse(tempTare) - sumT;
                            txtTotalTare.Text = String.Format("{0:#,##0}", sumT);
                        }
                        if (sumN > int.Parse(tempNet))
                        {
                            sumN = sumN - int.Parse(tempNet);
                            txtTotalNet.Text = String.Format("{0:#,##0}", sumN);
                        }
                        else
                        {
                            sumN = int.Parse(tempNet) - sumN;
                            txtTotalNet.Text = String.Format("{0:#,##0}", sumN);
                        }
                        if (sumP > int.Parse(tempPallet))
                        {
                            sumP = sumP - int.Parse(tempPallet);
                            txtTotalPallet.Text = String.Format("{0:#,##0}", sumP);
                        }
                        else
                        {
                            sumP = int.Parse(tempPallet) - sumP;
                            txtTotalPallet.Text = String.Format("{0:#,##0}", sumP);
                        }

                    }
                }
            }
            catch
            {
                // CommonMessageBox.ShowMessageError(ex);
            }

        }
        private void btnWeightClear_Click(object sender, EventArgs e)
        {
            //var result = MessageBox.Show("Are you sure you want to Clear ?", "Delete?", MessageBoxButtons.YesNo);
            //if (result == DialogResult.Yes)
            if (CommonMessageBox.ShowMessageConfirmYN("Are you sure you want to Clear ?") == DialogResult.Yes)
            {
                dgvWeight_Disp.Rows.Clear();
                clearTextBox();
                // No = 1;
            }
        }
        #endregion weightScale

        #region toolbar
        private void acceptCargoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel4.Visible = true;
            panel1.Visible = true;

            //panel4.Dock = DockStyle.Top;

            //panel1.Dock = DockStyle.Top;

        }
        private void transactionHistoryToolStripMenuItem_Click(object sender, EventArgs e)
        {

            try
            {
                E_ICS.frmTransactionHistory th = new E_ICS.frmTransactionHistory();
                th.ShowDialog();
                //if (th.Visible)
                //{
                //    // wsd.Show();
                //}
                //else
                //{
                //    if (th.IsDisposed == true)
                //    {
                //        th = new E_ICS.frmTransactionHistory();
                //        th.Show();
                //    }
                //    else
                //    {
                //        th.Show();
                //    }

                //}

            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }
        }
        private void preManifestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                E_ICS.frmPreManifest pm = new E_ICS.frmPreManifest();
                pm.ShowDialog();
                //if (pm.Visible)
                //{
                //    // wsd.Show();
                //}
                //else
                //{
                //    if (pm.IsDisposed == true)
                //    {
                //        pm = new E_ICS.frmPreManifest();
                //        pm.Show();
                //    }
                //    else
                //    {
                //        pm.Show();
                //    }

                //}
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }

        }
        public void GetDataFromAgentSearch(string[] items2)
        {
            txtAgentCode.Text = items2[0];
            txtAgentName.Text = items2[1];
            string ews_required = items2[2];
            if (ews_required == "YES")
            {
                chk_ews.Checked = true;
            }
            else
            {
                chk_ews.Checked = false;
            }
        }


        private void WHInventoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ClearViewInventoryValue();
                E_ICS.frmWHInventory wi = new E_ICS.frmWHInventory(this);
                wi.ShowDialog();
                //if (wi.Visible)
                //{
                //    // wsd.Show();
                //}
                //else
                //{
                //    if (wi.IsDisposed == true)
                //    {
                //        wi = new E_ICS.frmWHInventory(this);
                //        wi.Show();
                //    }
                //    else
                //    {
                //        wi.Show();
                //    }

                //}
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }

        }
        private void ClearViewInventoryValue()
        {
            ViewEditWHInventory.MAWB_ID = "";
            ViewEditWHInventory.slip_id = "";
            ViewEditWHInventory.MAWB = "";
            ViewEditWHInventory.HAWB = "";
            ViewEditWHInventory.Flight_No = "";
            ViewEditWHInventory.Flight_Date = "";
            ViewEditWHInventory.Partial_Acc = "";
            ViewEditWHInventory.Piece = "";
            ViewEditWHInventory.Weight = "";
            ViewEditWHInventory.Last_Stored = "";
            ViewEditWHInventory.Last_Retrieved = "";
            ViewEditWHInventory.Status = "";
            ViewEditWHInventory.scale_id = "";
        }
        //  E_ICS.About h = new E_ICS.About();
        private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
        {

            E_ICS.About h = new E_ICS.About();
            h.ShowDialog();
            //if (h.Visible)
            //{
            //    // h.Show();
            //}
            //else
            //{
            //    if (h.IsDisposed == true)
            //    {
            //        h = new E_ICS.About();
            //        h.Show();
            //    }
            //    else
            //    {
            //        h.Show();
            //    }

            //}

        }
        private void weightSlipDisplayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // E_ICS.frmWeightSlipDisplay wsd = null;
            try
            {
                ClearViewInventoryValue();
                wsd = new E_ICS.frmWeightSlipDisplay(this);
                wsd.ShowDialog();
                //if (wsd.Visible)
                //{
                //    // wsd.Show();
                //}
                //else
                //{
                //    if (wsd.IsDisposed == true)
                //    {
                //        wsd = new E_ICS.frmWeightSlipDisplay(this);
                //        wsd.Show();
                //    }
                //    else
                //    {
                //        wsd.Show();
                //    }

                //}
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }

        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.Close();
            Logout();
            panel1.Visible = false;
            panel4.Visible = false;
            //Weighting = Weighting * 0;
        }
        #endregion toolbar

        #region MAWB
        private void btnAgentSearch_Click(object sender, EventArgs e)
        {
            try
            {
                E_ICS.frmAgentSearch a = new E_ICS.frmAgentSearch(this);
                if (a.ShowDialog() == DialogResult.Yes)
                {
                    txtAgentCode.Text = ValueTofrmAddMAWB.SelAgentCode;
                    txtAgentName.Text = ValueTofrmAddMAWB.SelAgentName;
                    string ews_required = ValueTofrmAddMAWB.SelEws;
                    if (ews_required == "YES")
                    {
                        chk_ews.Checked = true;
                    }
                    else
                    {
                        chk_ews.Checked = false;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        private void btnMAWBClear_Click(object sender, EventArgs e)
        {
            try
            {
                //var result = MessageBox.Show("Are you sure you want to Clear All ?", "Delete?", MessageBoxButtons.YesNo);
                //if (result == DialogResult.Yes)
                if (CommonMessageBox.ShowMessageConfirmYN("Are you sure you want to Clear All ?") == DialogResult.Yes)
                {
                    clearAll();
                    ResetAll();
                    setsncmain();

                }

            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void setsncmain()
        {
            radioButton1.Checked = true;
            radioButton1.Focus();
            //hrow new NotImplementedException();
        }
        private void btnShowHistory_Click(object sender, EventArgs e)
        {
            try
            {
                SentValueSCN();
                E_ICS.frmWeightSlipDisplay wsd = new E_ICS.frmWeightSlipDisplay(this);
                wsd.ShowDialog();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }

        }

        private void SentValueSCN()
        {


            ViewEditWeightSlip.flagfromViewEditWeightSlip = -1;
            ViewEditWeightSlip.MAWB = txtPrefix.Text + txtSerial.Text;
            ViewEditWeightSlip.HAWB = txtHAWB.Text;
            ViewEditWeightSlip.Nature_of_Goods = txtNatureGood.Text;

            ViewEditWeightSlip.Flight_Date = txtFltDate.Text;
            ViewEditWeightSlip.Agent_Name = txtAgentName.Text;
            ViewEditWeightSlip.Agent = txtAgentCode.Text;
            ViewEditWeightSlip.Carrier = txtFltNo.Text.Substring(0, 2);
            ViewEditWeightSlip.Flight_No = txtFltNo.Text.Substring(2, txtFltNo.Text.Length - ViewEditWeightSlip.Carrier.Length); ;
            ViewEditWeightSlip.Scale_ID = lblScaleID.Text;
        }
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked)
            {
                txtHAWB.Text = "";
                txtHAWB.Enabled = false;
            }
            else
            {
                txtHAWB.Enabled = true;
            }
            ValueTofrmAddMAWB.consol = false;
        }
        private void btnMAWBAdd_Click(object sender, EventArgs e)
        {

            try
            {

                if (!String.IsNullOrEmpty(txtSerial.Text) && !String.IsNullOrEmpty(txtPrefix.Text))
                {
                    if (ValidateMawb())
                    {
                        MAWBSearch_Click();
                    }
                    else
                    {
                        //CommonMessageBox.ShowMessageWarning("Invalid MAWB Check Digit");
                        CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Digit"));
                    }
                }
                else
                {
                    MAWBSearch_Click();
                }

            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }

        }
        private void btnMAWBSearch_Click(object sender, EventArgs e)
        {

            try
            {
                btnMAWBSearch.Enabled = true;
                if (ValidateMawb())
                {
                    MAWBSearch_Click();
                }
                else
                {
                    //CommonMessageBox.ShowMessageWarning("Invalid MAWB Check Digit");
                    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Digit"));
                }
            }
            catch (Exception ex)
            {

                CommonMessageBox.ShowMessageError(ex);
            }
        }
        string mawb_no = string.Empty;
        public bool ValidateMawb()
        {
            try
            {
                mawb_no = txtPrefix.Text + txtSerial.Text;
                if ((mawb_no.Length == 11) || (mawb_no.Length == 16))
                {
                    string serial = mawb_no.Substring(3, 7);
                    string lastdigit = mawb_no.Substring(10, 1);
                    int intlastdigit = Convert.ToInt32(lastdigit);
                    int intserial = Convert.ToInt32(serial);
                    int cklastDig = intserial % 7;
                    if (intlastdigit == cklastDig)
                    {
                        return true;
                    }
                    else
                    {

                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {

                return false;
            }
        }
        private void MAWBSearch_Click()
        {
            string mawb = txtPrefix.Text + "-" + txtSerial.Text;
            string shipmenttype = string.Empty;
            AddMAWB am = new AddMAWB();
            ResultCheckMAWB result = null;
            try
            {
                if (radioButton2.Checked)
                {
                    shipmenttype = "NONCON";
                    if (!string.IsNullOrEmpty(txtPrefix.Text) && !string.IsNullOrEmpty(txtSerial.Text))
                    {
                        result = am.CheckMAWB(mawb, txtPrefix.Text, txtHAWB.Text, txtSerial.Text, shipmenttype, GlobalVariable.user.UserID, GlobalVariable.user.Device, GlobalVariable.user.ApplicationID);
                        if (result.Status == CHECK_MAWB_TYPE.Search)
                        {
                            E_ICS.frmMAWBsearch ms = new E_ICS.frmMAWBsearch(result.Data, this);
                            ///ms.ShowDialog();
                            if (ms.ShowDialog() == DialogResult.OK)
                            {
                                ResetAll();
                            }
                        }
                        else if (result.Status == CHECK_MAWB_TYPE.Add)
                        {
                            ValueTofrmAddMAWB.SelPrefix = txtPrefix.Text;
                            ValueTofrmAddMAWB.SelSerial = txtSerial.Text;
                            ValueTofrmAddMAWB.Selhawb = txtHAWB.Text;

                            E_ICS.frmAddMAWB a = new E_ICS.frmAddMAWB(this);
                            if (a.ShowDialog() == DialogResult.OK)
                            {
                                ResetAll();
                            }
                        }
                        else if (result.Status == CHECK_MAWB_TYPE.None)
                        {

                        }
                    }
                    else
                    {
                        //CommonMessageBox.ShowMessageWarning("The MAWB is missing");
                        CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_MAWB"));
                    }
                }
                else if (radioButton1.Checked)
                {
                    shipmenttype = "CONSOL";
                    if (!string.IsNullOrEmpty(txtPrefix.Text) && !string.IsNullOrEmpty(txtSerial.Text) && !string.IsNullOrEmpty(txtHAWB.Text))
                    {
                        result = am.CheckMAWB(mawb, txtPrefix.Text, txtHAWB.Text, txtSerial.Text, shipmenttype, GlobalVariable.user.UserID, GlobalVariable.user.Device, GlobalVariable.user.ApplicationID);
                        if (result.Status == CHECK_MAWB_TYPE.Search)
                        {
                            E_ICS.frmMAWBsearch ms = new E_ICS.frmMAWBsearch(result.Data, this);
                            ///ms.ShowDialog();
                            if (ms.ShowDialog() == DialogResult.OK)
                            {
                                ResetAll();
                            }
                        }
                        else if (result.Status == CHECK_MAWB_TYPE.Add)
                        {
                            ValueTofrmAddMAWB.SelPrefix = txtPrefix.Text;
                            ValueTofrmAddMAWB.SelSerial = txtSerial.Text;
                            ValueTofrmAddMAWB.Selhawb = txtHAWB.Text;

                            E_ICS.frmAddMAWB a = new E_ICS.frmAddMAWB(this);
                            if (a.ShowDialog() == DialogResult.OK)
                            {
                                ResetAll();
                            }
                        }
                        else if (result.Status == CHECK_MAWB_TYPE.None)
                        {

                        }
                    }
                    else
                    {
                        //CommonMessageBox.ShowMessageWarning("The MAWB and HAWB are required");
                        CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_required"));
                    }
                }
                //getShipmentType();

                //if (radioButton2.Checked)
                //{
                //    if (ValueTofrmAddMAWB.Selshipment_type == "NONCON" && ValueTofrmAddMAWB.SelSource == "LOCAL")
                //    {
                //        if (!string.IsNullOrEmpty(txtPrefix.Text) && !string.IsNullOrEmpty(txtSerial.Text))
                //        {
                //            getMAWBNonCon();
                //        }
                //        else
                //        {
                //            //CommonMessageBox.ShowMessageWarning("The MAWB is missing");
                //            CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_MAWB"));
                //        }
                //    }
                //    else if (ValueTofrmAddMAWB.Selshipment_type == "")
                //    {
                //        if (!string.IsNullOrEmpty(txtPrefix.Text) && !string.IsNullOrEmpty(txtSerial.Text))
                //        {
                //            getMAWBNonCon();
                //        }
                //        else
                //        {
                //            //CommonMessageBox.ShowMessageWarning("The MAWB is missing");
                //            CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_MAWB"));
                //        }
                //    }
                //    else if (ValueTofrmAddMAWB.Selshipment_type == "NONCON" && ValueTofrmAddMAWB.SelSource == "CARGOSPOT")
                //    {
                //        DialogResult result;
                //        result = CommonMessageBox.ShowMessageConfirmYN("This MAWB is already in CARGOSPOT. Are you want to add?");
                //        if (result == DialogResult.Yes)
                //        {
                //            getMAWBNonCon();
                //        }
                //    }
                //    else
                //    {
                //        //CommonMessageBox.ShowMessageError("Shipment Type Invalid");
                //        CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_Shipment_type"));
                //    }
                //}
                //else if (radioButton1.Checked)
                //{
                //    if (ValueTofrmAddMAWB.Selshipment_type == "CONSOL")
                //    {

                //        if (!string.IsNullOrEmpty(txtPrefix.Text) && !string.IsNullOrEmpty(txtSerial.Text) && !string.IsNullOrEmpty(txtHAWB.Text))
                //        {
                //            getMAWBConsol();
                //        }
                //        else
                //        {
                //            //CommonMessageBox.ShowMessageWarning("The MAWB and HAWB are required");
                //            CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_required"));
                //        }
                //    }
                //    else if (ValueTofrmAddMAWB.Selshipment_type == "")
                //    {
                //        if (!string.IsNullOrEmpty(txtPrefix.Text) && !string.IsNullOrEmpty(txtSerial.Text) && !string.IsNullOrEmpty(txtHAWB.Text))
                //        {
                //            getMAWBConsol();
                //        }
                //        else
                //        {
                //            //CommonMessageBox.ShowMessageWarning("The MAWB and HAWB are required");
                //            CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_required"));
                //        }
                //    }
                //    else if (ValueTofrmAddMAWB.SelSource == "CARGOSPOT")
                //    {
                //        DialogResult result;
                //        result = CommonMessageBox.ShowMessageConfirmYN("This MAWB is already in CARGOSPOT. Are you want to add?");
                //        if (result == DialogResult.Yes)
                //        {
                //            getMAWBConsol();
                //        }
                //    }
                //    else
                //    {
                //        //CommonMessageBox.ShowMessageError("Shipment Type Invalid");
                //        CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_Shipment_type"));
                //    }
                //}
            }
            catch (Exception)
            {

                //
            }
        }
        public void getDataFromMAWBSearch(string[] items3)
        {
            txtHAWB.Text = items3[0];
            txtFltNo.Text = items3[1];
            txtFltDate.Text = items3[2];
            txtDest.Text = items3[3];
            seq = int.Parse(items3[4]) + 1;
            txtSeq.Text = seq.ToString();
            txtAgentCode.Text = items3[5];
            txtAgentName.Text = items3[6];
            txtNatureGood.Text = items3[7];
            type = items3[8];
            if (type == "CONSOL")
            {
                radioButton1.Checked = true;

            }
            else
            {
                radioButton2.Checked = true;
            }
            if (int.Parse(txtSeq.Text) > 1)
            {
                checkBox1.Checked = true;
                if (checkBox1.Checked)
                {
                    partialflag = "YES";
                }
            }
            else
            {
                partialflag = "NO";
            }
        }
        public void getDataFromAddMAWB(string[] items4)
        {
            txtPrefix.Text = items4[0];
            txtSerial.Text = items4[1];
            txtHAWB.Text = items4[2];
            txtFltNo.Text = items4[3];
            txtFltDate.Text = items4[4];
            txtDest.Text = items4[5];
            txtNatureGood.Text = items4[6];
            txtPieces.Text = items4[7];
            type = items4[8];
            txtSeq.Text = items4[9];
            if (type == "CONSOL")
            {
                radioButton1.Checked = true;

            }
            else
            {
                radioButton2.Checked = true;
            }
            if (int.Parse(txtSeq.Text) > 1)
            {
                checkBox1.Checked = true;
                if (checkBox1.Checked)
                {
                    partialflag = "YES";
                }
            }
            else
            {
                partialflag = "NO";
            }
        }
        #endregion MAWB

        #region Dimension
        private void btnDimClear_Click(object sender, EventArgs e)
        {
            //var result = MessageBox.Show("Are you sure you want to Clear ?", "Delete?", MessageBoxButtons.YesNo);
            //if (result == DialogResult.Yes)
            if (CommonMessageBox.ShowMessageConfirmYN("Are you sure you want to Clear ?") == DialogResult.Yes)
            {
                dgvDim.Rows.Clear();
                lblTotal.Text = "0";
            }
        }
        private void dgvDim_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == dgvDim.Columns["DimDel"].Index && e.RowIndex >= 0)    // Delete Dim
                {

                    //var result = MessageBox.Show("Are you sure you want to delete this line ?", "Delete?", MessageBoxButtons.YesNo);
                    //if (result == DialogResult.Yes)
                    if (CommonMessageBox.ShowMessageConfirmYN("Are you sure you want to Delete this line ?") == DialogResult.Yes)
                    {
                        if (e.RowIndex == 0)
                        {
                            if (dgvDim.Rows[0].Cells[0].Value == null
                                || dgvDim.Rows[0].Cells[1].Value == null
                                || dgvDim.Rows[0].Cells[2].Value == null
                                || dgvDim.Rows[0].Cells[3].Value == null)
                            {
                                // MessageBox.Show("");
                                dgvDim.Rows.RemoveAt(e.RowIndex);
                                setRowNumber(dgvDim);
                                CallblTotal(dgvDim);
                            }
                            else
                            {
                                //var result = MessageBox.Show("Are you sure you want to delete this line ?", "Delete?", MessageBoxButtons.YesNo);
                                //if (result == DialogResult.Yes)
                                // {
                                dgvDim.Rows.RemoveAt(e.RowIndex);
                                setRowNumber(dgvDim);
                                CallblTotal(dgvDim);
                                // }
                            }

































































































































































































































                        }
                        else
                        {
                            //  var result1 = MessageBox.Show("Are you sure you want to delete this line ?", "Delete?", MessageBoxButtons.YesNo);
                            //  if (result1 == DialogResult.Yes)
                            // {
                            dgvDim.Rows.RemoveAt(e.RowIndex);
                            setRowNumber(dgvDim);
                            CallblTotal(dgvDim);
                            // }
                        }
                    }

                }
                else
                {
                    //// check dim L W H is null 
                    if (e.ColumnIndex == 3 /*dgvDim.Columns["DimPcs"].Index*/ && e.RowIndex >= 0)
                    {

                        if (dgvDim.Rows[e.RowIndex].Cells[0].Value == null
                             || dgvDim.Rows[e.RowIndex].Cells[1].Value == null
                             || dgvDim.Rows[e.RowIndex].Cells[2].Value == null)
                        {
                            CommonMessageBox.ShowMessageError(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_inser_digit"));
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                try
                {
                    dgvDim.Rows.RemoveAt(e.RowIndex);
                }
                catch (Exception)
                {

                    //throw;
                }
                // CommonMessageBox.ShowMessageError(ex);
            }

        }
        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            //try
            //{
            //    if (e.ColumnIndex == dgvDim.Columns["DimDel"].Index && e.RowIndex >= 0)    // Delete Dim
            //    {
            //        //string temp = "0";
            //        //try
            //        //{

            //        //    //temp = dgvDim.Rows[e.RowIndex].Cells[3].Value.ToString();
            //        //}
            //        //catch (Exception)
            //        //{
            //        //    //
            //        //}
            //        // sumPiecs = sumPiecs - int.Parse(temp);
            //        var result = MessageBox.Show("Are you sure you want to delete this line ?", "Delete?", MessageBoxButtons.YesNo);
            //        if (result == DialogResult.Yes)
            //        {
            //            if (e.RowIndex == 0)
            //            {
            //                if (dgvDim.Rows[0].Cells[0].Value.ToString().Equals("")
            //                    || dgvDim.Rows[0].Cells[1].Value.ToString().Equals("")
            //                    || dgvDim.Rows[0].Cells[2].Value.ToString().Equals("")
            //                    || dgvDim.Rows[0].Cells[3].Value.ToString().Equals(""))
            //                {
            //                   // MessageBox.Show("");
            //                }
            //                else
            //                {
            //                    //var result = MessageBox.Show("Are you sure you want to delete this line ?", "Delete?", MessageBoxButtons.YesNo);
            //                    //if (result == DialogResult.Yes)
            //                    // {
            //                    dgvDim.Rows.RemoveAt(e.RowIndex);
            //                    setRowNumber(dgvDim);
            //                    CallblTotal(dgvDim);
            //                    // }
            //                }

            //                //if (sumPiecs > int.Parse(temp))
            //                //{
            //                //    sumPiecs = sumPiecs - int.Parse(temp);
            //                //    lblTotal.Text = sumPiecs.ToString();
            //                //}
            //                //else
            //                //{
            //                //    sumG = int.Parse(temp) - sumG;
            //                //    lblTotal.Text = sumPiecs.ToString();
            //                //}
            //            }
            //            else
            //            {
            //                var result1 = MessageBox.Show("Are you sure you want to delete this line ?", "Delete?", MessageBoxButtons.YesNo);
            //                if (result1 == DialogResult.Yes)
            //                {
            //                    dgvDim.Rows.RemoveAt(e.RowIndex);
            //                    setRowNumber(dgvDim);
            //                    CallblTotal(dgvDim);
            //                }
            //            }
            //        }

            //    }
            //    else
            //    {
            //        //MessageBox.Show("ok");
            //    }
            //}
            //catch (Exception ex)
            //{
            //    try
            //    {
            //        dgvDim.Rows.RemoveAt(e.RowIndex);
            //    }
            //    catch (Exception)
            //    {

            //        //throw;
            //    }
            //    // CommonMessageBox.ShowMessageError(ex);
            //}

        }
        private void CallblTotal(DataGridView a)
        {
            double sum = 0;
            try
            {

                for (int i = 0; i < a.Rows.Count; i++)
                {
                    sum += Convert.ToDouble(dgvDim.Rows[i].Cells[3].Value);
                }
                lblTotal.Text = String.Format("{0:##,#}", sum);
            }
            catch (Exception)
            {

                // throw;
            }

        }
        private void dgvDim_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                // MessageBox.Show(   dgvDim.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.GetType().ToString());
                string value_dim = "";
                value_dim = dgvDim.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                for (int i = 0; i < value_dim.Count(); i++)
                {
                    char ck = dgvDim.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()[i];
                    if (Char.IsDigit(ck))
                    {

                    }
                    else
                    {
                        //CommonMessageBox.ShowMessageError("Please insert digit only");
                        CommonMessageBox.ShowMessageError(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_inser_digit"));
                        dgvDim.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dgvDim.Focus();
                    }
                }
                if (value_dim.Count() == 1)
                {
                    if (value_dim.Equals("0"))
                    {
                        //CommonMessageBox.ShowMessageError(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_inser_digit"));
                        CommonMessageBox.ShowMessageError("It must more than zero!");
                        dgvDim.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dgvDim.Focus();
                    }

                }

                if (e.ColumnIndex == 3 /*dgvDim.Columns["DimPcs"].Index*/ && e.RowIndex >= 0)
                {
                    CallblTotal(dgvDim);
                    //string value = dgvDim.Rows[e.RowIndex].Cells[3].Value.ToString();
                    //sumPiecs = sumPiecs + int.Parse(value);
                    //lblTotal.Text = sumPiecs.ToString();
                    if (dgvDim.Rows[e.RowIndex].Cells[0].Value == null
                        || dgvDim.Rows[e.RowIndex].Cells[1].Value == null
                        || dgvDim.Rows[e.RowIndex].Cells[2].Value == null)
                    {
                        CommonMessageBox.ShowMessageError(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_Check_inser_digit"));
                    }
                }

            }
            catch (Exception ex)
            {
                // CommonMessageBox.ShowMessageError(ex);
            }

        }
        private void dgvDim_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {
                setRowNumber(dgvDim);
                CallblTotal(dgvDim);
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        #endregion Dimension

        #region OtherInfo
        private void btnOtherInfoClear_Click(object sender, EventArgs e)
        {
            //var result = MessageBox.Show("Are you sure you want to Clear ?", "Delete?", MessageBoxButtons.YesNo);
            //if (result == DialogResult.Yes)
            if (CommonMessageBox.ShowMessageConfirmYN("Are you sure you want to Clear ?") == DialogResult.Yes)
            {
                dgvOthInfo.Rows.Clear();
            }
        }
        private void btnAddOtherInfo_Click(object sender, EventArgs e)
        {
            try
            {
                E_ICS.frmAddOtherInfo o = new E_ICS.frmAddOtherInfo(this);
                o.ShowDialog();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }

        }
        public void getDataFromAddOtherInfo(string[] items5)
        {
            try
            {
                dgvOthInfo.Rows.Add(items5[0], items5[1]);
                setRowNumber(dgvOthInfo);
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }

        }
        private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == dgvOthInfo.Columns["OtherDel"].Index && e.RowIndex >= 0)
                {
                    //var result = MessageBox.Show("Are you sure you want to Delete line ?", "Delete?", MessageBoxButtons.YesNo);
                    //if (result == DialogResult.Yes)
                    if (CommonMessageBox.ShowMessageConfirmYN("Are you sure you want to Delete this line ?") == DialogResult.Yes)
                    {
                        dgvOthInfo.Rows.RemoveAt(e.RowIndex);
                        setRowNumber(dgvOthInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                // CommonMessageBox.ShowMessageError(ex);
            }

        }
        #endregion OtherInfo

        #region Save
        private void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult result;
            slipid = string.Empty;
            mawbid = string.Empty;
            bool isRetry = false;
            bool isRetryMAWB = false;
            int mawbResult = 0;
            try
            {
                if (!ValidateMawb())
                {
                    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Digit"));
                    return;
                }
                if (!ValidateWeightDim())
                {
                    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Dimension"));
                    return;
                }
                if (!ValidateAgent())
                {
                    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_agencode"));
                    return;
                }
                if (!ValidatePcs())
                {
                    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Pieces"));
                    return;
                }
                result = CommonMessageBox.displayConfirmSave();
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    ////if generate slip number fail
                    //if (!genSlipNO())
                    //{
                    //    return;
                    //}
                    if (chk_ews.Checked)
                    {
                        ewsflag = "YES";
                    }
                    else
                    {
                        ewsflag = "NO";
                    }
                    try
                    {
                        //using (System.Transactions.TransactionScope tran = new System.Transactions.TransactionScope())
                        //{
                        do
                        {
                            try
                            {
                                isRetryMAWB = false;
                                mawbid = string.Empty;
                                slipid = string.Empty;
                                using (Entities ent = new Entities())
                                {
                                    ent.Open();
                                    mawbResult = saveMAWB(ent, null);
                                }
                                if (mawbResult == -999)
                                {
                                    if (!string.IsNullOrEmpty(mawbid))
                                    {
                                        DeleteMAWB(mawbid);
                                        return;
                                    }
                                }
                                else if (mawbResult == -1)
                                {
                                    if (string.IsNullOrEmpty(mawbid))
                                    {
                                        isRetryMAWB = true;
                                    }
                                }

                                if (isRetryMAWB)
                                {
                                    if (CommonMessageBox.ShowMessageConfirmYN("Save MAWB fail do you want to retry?") == System.Windows.Forms.DialogResult.No)
                                    {
                                        isRetryMAWB = false;
                                    }
                                }
                            }
                            catch (Exception exMawb)
                            {
                                if (!string.IsNullOrEmpty(mawbid))
                                {
                                    DeleteMAWB(mawbid);
                                }
                                CommonMessageBox.ShowMessageError(exMawb);
                            }
                        } while (isRetryMAWB);  //if MAWB save fail

                        //if generate slip number fail
                        if (!genSlipNO())
                        {
                            //delete MAWB
                            return;
                        }
                        //loop to confirm user to retry save if error
                        do
                        {
                            using (Entities en = new Entities())
                            {
                                slipid = string.Empty;
                                en.Open();
                                //DbConnection con = en.GetConnection();
                                //using (DbTransaction tran = con.BeginTransaction())
                                DbTransaction tran = null;
                                {
                                    try
                                    {
                                        isRetry = false;
                                        //if (genSlipNO(en, tran))
                                        //{
                                        if (InsertWeightSlip(en, tran))
                                        {
                                            if (InsertWeightRecord(en, tran))
                                            {
                                                if (InsertDimensionRecord(en, tran))
                                                {
                                                    if (InsertCommentRecord(en, tran))
                                                    {
                                                        //tran.Commit();
                                                        GlobalVariable.cerent = -1;
                                                        ReadOnly();
                                                    }
                                                    else
                                                    {
                                                        //tran.Rollback();
                                                        isRetry = true;
                                                    }
                                                }
                                                else
                                                {
                                                    //tran.Rollback();
                                                    isRetry = true;
                                                }
                                            }
                                            else
                                            {
                                                //tran.Rollback();
                                                isRetry = true;
                                            }
                                        }
                                        else
                                        {
                                            //tran.Rollback();
                                            isRetry = true;
                                        }
                                        //InsertWeightSlip(en, tran)
                                        //InsertWeightRecord(en, tran);
                                        //InsertDimensionRecord(en, tran);
                                        //InsertCommentRecord(en, tran);
                                        //tran.Commit();
                                        //GlobalVariable.cerent = -1;
                                        //ReadOnly();
                                        //}
                                        //else
                                        //{
                                        //    tran.Rollback();
                                        //    isRetry = true;
                                        //}
                                    }
                                    catch (InvalidOperationException)
                                    {
                                        isRetry = true;
                                    }
                                    catch (SqlException)
                                    {
                                        //tran.Rollback();
                                        isRetry = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        //tran.Rollback();
                                        isRetry = true;
                                        CommonMessageBox.ShowMessageError(ex);
                                    }
                                }
                            }
                            if (isRetry)
                            {
                                if (CommonMessageBox.ShowMessageConfirmYN("Save fail.Do you want to retry save MAWB?") == System.Windows.Forms.DialogResult.No)
                                {
                                    isRetry = false;
                                    if (!string.IsNullOrEmpty(mawbid))
                                    {
                                        DeleteSlipIdRelate(slipid, mawbid);
                                        DeleteMAWB(mawbid);
                                    }
                                }
                                else
                                {
                                    DeleteSlipIdRelate(slipid, mawbid);
                                }
                            }
                        } while (isRetry);// retry save
                    }
                    catch (Exception ex)
                    {
                        //delete MAWB
                        if (!string.IsNullOrEmpty(mawbid))
                        {
                            DeleteSlipIdRelate(slipid, mawbid);
                            DeleteMAWB(mawbid);
                        }
                        CommonMessageBox.ShowMessageError(ex);
                    }
                }
                //}
                //else
                //{
                //    //CommonMessageBox.ShowMessageWarning("Pieces Count does not Match");
                //    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Pieces"));
                //}
                //}
                //else
                //{
                //    //CommonMessageBox.ShowMessageWarning("The agent code or agent name is missing");
                //    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_Msgbox_agencode"));
                //}
                //}
                //else
                //{
                //    //CommonMessageBox.ShowMessageWarning("Please enter Weight Entries and Dimension");
                //    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Dimension"));
                //}
                //}
                //else
                //{
                //    //CommonMessageBox.ShowMessageWarning("Invalid MAWB Check Digit");
                //    CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourseValue("scn_Main2_com_msgbox_ck_Digit"));
                //}
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private bool DeleteMAWB(string mawb_id)
        {
            bool returnResult = true;
            DataSet ds = new DataSet();
            string status = string.Empty;
            string errorCode = string.Empty;
            string message = string.Empty;
            try
            {
                using (Entities entity = new Entities())
                {
                    entity.Open();
                    DbCommand cmd = entity.CreateCommand("usp_DeleteMAWBRecord");
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchApplicationID", GlobalVariable.user.ApplicationID));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchMAWB_ID", mawb_id));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchDevice", GlobalVariable.user.Device));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchUserID", GlobalVariable.user.UserID));
                    DbDataAdapter adapter = entity.CreateDataAdapter(cmd);
                    adapter.Fill(ds);
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        status = ds.Tables[0].Rows[0]["Status"].ToString();
                        errorCode = ds.Tables[0].Rows[0]["ErrorCode"].ToString();
                        message = ds.Tables[0].Rows[0]["Message"].ToString();
                        if (!status.Equals("PASS"))
                        {
                            returnResult = false;
                            CommonMessageBox.ShowMessageError(string.Format("{0}\r\n{1}", errorCode, message));
                        }

                    }
                    else
                    {
                        returnResult = false;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
                returnResult = false;
            }

            return returnResult;
        }

        private bool DeleteSlipIdRelate(string slip_id, string mawb_id)
        {
            bool returnResult = true;
            DataSet ds = new DataSet();
            string status = string.Empty;
            string errorCode = string.Empty;
            string message = string.Empty;
            int affectRow = 0;
            DbCommand cmd = null;
            DbDataAdapter adapter = null;

            try
            {
                using (Entities entity = new Entities())
                {
                    entity.Open();
                    if (!string.IsNullOrEmpty(slip_id))
                    {
                        cmd = entity.CreateCommand(string.Format("DELETE FROM t_eics_comment WHERE slip_id='{0}'", slip_id));
                        cmd.CommandType = CommandType.Text;
                        affectRow = cmd.ExecuteNonQuery();

                        cmd.CommandText = string.Format("DELETE FROM t_eics_dimension WHERE slip_id='{0}'", slip_id);
                        affectRow = cmd.ExecuteNonQuery();

                        cmd.CommandText = string.Format("DELETE FROM t_eics_weight WHERE slip_id='{0}'", slip_id);
                        affectRow = cmd.ExecuteNonQuery();
                    }

                    if (!string.IsNullOrEmpty(mawb_id))
                    {
                        cmd = entity.CreateCommand(string.Format("DELETE FROM t_eics_wgt_slip WHERE mawb_id='{0}'", mawb_id));
                        affectRow = cmd.ExecuteNonQuery();
                    }

                    //cmd.CommandText = "usp_DeleteWeightSlipRecord";
                    //cmd.CommandType = CommandType.StoredProcedure;
                    //cmd.Parameters.Add(entity.CreateParameter("@in_vchApplicationID", GlobalVariable.user.ApplicationID));
                    //cmd.Parameters.Add(entity.CreateParameter("@in_vchWeightSlipID", slip_id));
                    //cmd.Parameters.Add(entity.CreateParameter("@in_vchDevice", GlobalVariable.user.Device));
                    //cmd.Parameters.Add(entity.CreateParameter("@in_vchUserID", GlobalVariable.user.UserID));

                    //adapter = entity.CreateDataAdapter(cmd);
                    //adapter.Fill(ds);
                    //if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    //{
                    //    status = ds.Tables[0].Rows[0]["Status"].ToString();
                    //    errorCode = ds.Tables[0].Rows[0]["ErrorCode"].ToString();
                    //    message = ds.Tables[0].Rows[0]["Message"].ToString();
                    //    if (!status.Equals("PASS"))
                    //    {
                    //        returnResult = false;
                    //        CommonMessageBox.ShowMessageError(string.Format("{0}\r\n{1}", errorCode, message));
                    //    }

                    //}
                    //else
                    //{
                    //    returnResult = false;
                    //}
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
                returnResult = false;
            }

            return returnResult;
        }

        private bool ValidateAgent()
        {
            try
            {
                if (!string.IsNullOrEmpty(txtAgentCode.Text) && !string.IsNullOrEmpty(txtAgentName.Text))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {

                return false;
            }
        }

        private bool ValidatePcs()
        {
            try
            {
                int pcs = Convert.ToInt32(txtPieces.Text);
                int pcsdimtotal = 0;
                for (int i = 0; i < dgvDim.RowCount - 1; i++)
                {
                    pcsdimtotal = pcsdimtotal + Convert.ToInt32(dgvDim.Rows[i].Cells["DimPcs"].Value.ToString());
                }
                // MessageBox.Show(pcsdimtotal.ToString());
                if (pcs > 0 && pcsdimtotal > 0)
                {
                    if (pcs == pcsdimtotal)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }

            }
            catch (Exception)
            {


                return false;
            }


        }
        private bool ValidateWeightDim()
        {
            try
            {
                if (dgvWeight_Disp.RowCount > 1 && dgvDim.RowCount > 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {

                return false;
            }
        }
        private bool genSlipNO()
        {
            bool result = true;
            //int runingNO = 0;
            //runingNO++;
            //slipNO = slipyear + runingNO.ToString("D5");
            //txtSlipNO.Text = slipNO;

            //START Test chen 2015.05.12
            try
            {
                txtSlipNO.Text = string.Empty;
                System.Data.DataSet dsSlip = new DataSet();
                using (ECS.DAL.Entities entity = new ECS.DAL.Entities())
                {
                    entity.Open();
                    System.Data.Common.DbCommand cmd = entity.CreateCommand("usp_GetNextSlipNumber");
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchApplicationID", GlobalVariable.user.ApplicationID));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchDevice", GlobalVariable.user.Device));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchUserID", GlobalVariable.user.UserID));
                    System.Data.Common.DbDataAdapter adapter = entity.CreateDataAdapter(string.Empty);
                    adapter.SelectCommand = cmd;
                    adapter.Fill(dsSlip, "result");
                    if (dsSlip != null && dsSlip.Tables.Count > 0)
                    {
                        if (dsSlip.Tables[0].Rows[0]["status"].Equals("PASS"))
                        {
                            txtSlipNO.Text = dsSlip.Tables[0].Rows[0]["slip_number"] != DBNull.Value ? dsSlip.Tables[0].Rows[0]["slip_number"].ToString() : string.Empty;
                        }
                        else
                        {
                            string msg = dsSlip.Tables[0].Rows[0]["ErrorCode"] != DBNull.Value ? dsSlip.Tables[0].Rows[0]["ErrorCode"].ToString() : string.Empty;
                            msg = msg + (dsSlip.Tables[0].Rows[0]["Message"] != DBNull.Value ? dsSlip.Tables[0].Rows[0]["Message"].ToString() : string.Empty).ToString();
                            CommonMessageBox.ShowMessageWarning(msg);
                            result = false;
                        }
                    }
                    else
                    {

                        CommonMessageBox.ShowMessageWarning("Generate weight slip number fail");
                        result = false;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
                result = false;
            }
            return result;
            //END Test chen 2015.05.12


            //SqlCommand cmd = null;
            //try
            //{
            //    cmd = new SqlCommand();
            //    sqlCon.Open();
            //    cmd.CommandText = "usp_get_lastslip";
            //    cmd.CommandText = "usp_GetNextSlipNumber";
            //    cmd.CommandType = CommandType.StoredProcedure;
            //    cmd.Connection = sqlCon;
            //    SqlDataAdapter da = new SqlDataAdapter(cmd);
            //    dataset = new DataSet();
            //    da.Fill(dataset, "lastslip");
            //    // string status = dataset.Tables[0].Rows[0]["Status"].ToString();

            //    txtSlipNO.Text = dataset.Tables[0].Rows[0]["lastslip"].ToString();
            //    //MessageBox.Show(slipid);

            //}
            //catch (Exception objEx)
            //{
            //    CommonMessageBox.ShowMessageError(objEx);

            //}
            //finally
            //{
            //    if (sqlCon != null && sqlCon.State == ConnectionState.Open)
            //    {
            //        sqlCon.Close();
            //    }
            //}
        }

        private bool genSlipNO(Entities entity, DbTransaction tran)
        {
            bool result = true;
            try
            {
                txtSlipNO.Text = string.Empty;
                System.Data.DataSet dsSlip = new DataSet();
                //using (ECS.DAL.Entities entity = new ECS.DAL.Entities())
                {
                    //entity.Open();
                    System.Data.Common.DbCommand cmd = entity.CreateCommand("usp_GetNextSlipNumber");
                    cmd.CommandType = CommandType.StoredProcedure;
                    //cmd.Transaction = tran;
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchApplicationID", GlobalVariable.user.ApplicationID));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchDevice", GlobalVariable.user.Device));
                    cmd.Parameters.Add(entity.CreateParameter("@in_vchUserID", GlobalVariable.user.UserID));
                    System.Data.Common.DbDataAdapter adapter = entity.CreateDataAdapter(string.Empty);
                    adapter.SelectCommand = cmd;
                    adapter.Fill(dsSlip, "result");
                    if (dsSlip != null && dsSlip.Tables.Count > 0)
                    {
                        if (dsSlip.Tables[0].Rows[0]["status"].Equals("PASS"))
                        {
                            txtSlipNO.Text = dsSlip.Tables[0].Rows[0]["slip_number"] != DBNull.Value ? dsSlip.Tables[0].Rows[0]["slip_number"].ToString() : string.Empty;
                        }
                        else
                        {
                            string msg = dsSlip.Tables[0].Rows[0]["ErrorCode"] != DBNull.Value ? dsSlip.Tables[0].Rows[0]["ErrorCode"].ToString() : string.Empty;
                            msg = msg + (dsSlip.Tables[0].Rows[0]["Message"] != DBNull.Value ? dsSlip.Tables[0].Rows[0]["Message"].ToString() : string.Empty).ToString();
                            CommonMessageBox.ShowMessageWarning(msg);
                            result = false;
                        }
                    }
                    else
                    {

                        CommonMessageBox.ShowMessageWarning("Generate weight slip number fail");
                        result = false;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
                result = false;
            }
            return result;
        }

        private int saveMAWB(Entities en, DbTransaction tran)
        {
            int result = 0;
            //SqlCommand cmd = new SqlCommand();
            DbCommand cmd = en.CreateCommand("usp_SaveMAWB");
            //cmd.Transaction = tran;
            try
            {
                string mawb = txtPrefix.Text + txtSerial.Text;
                //string prefix = mawb.Substring(0, 3);
                //string serial = mawb.Substring(3, 8);
                DateTime dt = DateTime.Parse(txtFltDate.Text);
                string fltdate = String.Format("{0:MM-dd-yyyy}", dt);
                string fullFlightNo = txtFltNo.Text;
                string carrier = fullFlightNo.Substring(0, 2);
                string fltno = fullFlightNo.Substring(2, fullFlightNo.Length - 2);
                //sqlCon.Open();
                //cmd.CommandTimeout = 180;
                //cmd.CommandText = "usp_SaveMAWB";
                cmd.CommandType = CommandType.StoredProcedure;
                //cmd.Connection = sqlCon;
                cmd.Parameters.Add(en.CreateParameter("@in_vchApplicationID", appId));
                cmd.Parameters.Add(en.CreateParameter("@in_vchMAWB", mawb));
                cmd.Parameters.Add(en.CreateParameter("@in_vchMAWBPrefix", txtPrefix.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_vchMAWBSerial", txtSerial.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_vchHAWB", txtHAWB.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_intMAWBPartialSeq", txtSeq.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_vchShipmentType", type));
                cmd.Parameters.Add(en.CreateParameter("@in_vchSlipType", "LOCAL"));
                cmd.Parameters.Add(en.CreateParameter("@in_vchPartialAcceptanceFlag", partialflag));
                cmd.Parameters.Add(en.CreateParameter("@in_vchCarrier", carrier));
                cmd.Parameters.Add(en.CreateParameter("@in_vchFlightNumber", fltno));
                cmd.Parameters.Add(en.CreateParameter("@in_dtFlightDate", fltdate));
                cmd.Parameters.Add(en.CreateParameter("@in_vchDestination", txtDest.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_vchAgentCode ", txtAgentCode.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_vchAgentName", txtAgentName.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_vchNatureOfGoods", txtNatureGood.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_intPieceCount", txtPieces.Text));
                cmd.Parameters.Add(en.CreateParameter("@in_vchEWSRequired", ewsflag));
                cmd.Parameters.Add(en.CreateParameter("@in_vchFBLFlightNumber", GlobalVariable.fbl_fltNO.Substring(2, GlobalVariable.fbl_fltNO.Length - 2)));
                cmd.Parameters.Add(en.CreateParameter("@in_vchDevice", GlobalVariable.Device));
                cmd.Parameters.Add(en.CreateParameter("@in_vchUserID", GlobalVariable.userName));

                DbDataAdapter da = en.CreateDataAdapter(cmd);
                dataset = new DataSet();
                da.Fill(dataset, "testSaveMAWB");
                string status = dataset.Tables[0].Rows[0]["Status"].ToString();
                string errorCode = dataset.Tables[0].Rows[0]["ErrorCode"].ToString();
                string message = dataset.Tables[0].Rows[0]["Message"].ToString();
                if (status == "PASS")
                {
                    mawbid = dataset.Tables[0].Rows[0]["mawb_id"].ToString();
                }
                else
                {
                    result = -1;
                    CommonMessageBox.ShowMessageWarning(string.Format("{0}\r\n{1}", errorCode, message));
                }
            }
            catch (SqlException exSql)
            {
                CommonMessageBox.ShowMessageError(exSql);
                result = -999;
            }
            catch (Exception ex)
            {
                //string str = "You must enter 11 digits of MAWB";
                CommonMessageBox.ShowMessageError(ex);
                //throw ex;
                result = -1;
            }

            //finally
            //{
            //    if (sqlCon != null && sqlCon.State != ConnectionState.Closed)
            //    {
            //        sqlCon.Close();
            //    }
            //}

            return result;
        }

        private bool InsertWeightSlip(Entities en, DbTransaction tran)
        {
            bool result = true;
            //SqlCommand cmd = new SqlCommand();

            //try
            //{
            //    sqlCon.Open();
            DbCommand cmd = en.CreateCommand("usp_InsertWeightSlip");
            cmd.CommandText = "usp_InsertWeightSlip";
            cmd.CommandType = CommandType.StoredProcedure;
            //cmd.Transaction = tran;
            //cmd.Connection = sqlCon;
            cmd.Parameters.Add(en.CreateParameter("@in_vchApplicationID", appId));
            cmd.Parameters.Add(en.CreateParameter("@in_vchMAWB_ID", mawbid));
            cmd.Parameters.Add(en.CreateParameter("@in_vchScaleID", lblScaleID.Text));
            cmd.Parameters.Add(en.CreateParameter("@in_vchStationID", GlobalVariable.user.Device));
            cmd.Parameters.Add(en.CreateParameter("@in_vchSlipNumber", txtSlipNO.Text));
            cmd.Parameters.Add(en.CreateParameter("@in_vchDevice", GlobalVariable.Device));
            cmd.Parameters.Add(en.CreateParameter("@in_vchUserID", GlobalVariable.userName));
            //cmd.CommandTimeout = 180;
            DbDataAdapter da = en.CreateDataAdapter(cmd);
            dataset = new DataSet();
            da.Fill(dataset, "InsertWeightSlip");
            string status = dataset.Tables[0].Rows[0]["Status"].ToString();
            string errorCode = dataset.Tables[0].Rows[0]["ErrorCode"].ToString();
            string message = dataset.Tables[0].Rows[0]["Message"].ToString();

            if (status != "PASS")
            {
                result = false;
                CommonMessageBox.ShowMessageWarning(string.Format("{0}\r\n{1}\r\n[Insert Weight Slip]", errorCode, message));
            }
            else
            {
                slipid = dataset.Tables[0].Rows[0]["slip_id"].ToString();
                if (string.IsNullOrEmpty(slipid))
                {
                    result = false;
                    CommonMessageBox.ShowMessageWarning("Invalid slip_id\r\n[Insert Weight Slip]");
                }
            }
            //sqlCon.Close();
            //}
            //catch (Exception objEx)
            //{
            //    CommonMessageBox.ShowMessageError(objEx);
            //}
            return result;
        }
        private bool InsertWeightRecord(Entities en, DbTransaction tran)
        {
            bool result = true;
            //SqlCommand cmd = new SqlCommand();
            //try
            //{
            //    sqlCon.Open();
            DbCommand cmd = en.CreateCommand("usp_InsertWeightRecord");
            //cmd.Transaction = tran;
            cmd.CommandType = CommandType.StoredProcedure;
            for (int i = 0; i < dgvWeight_Disp.Rows.Count - 1; i++)
            {
                //cmd.CommandTimeout = 180;
                //cmd.CommandText = "usp_InsertWeightRecord";
                //cmd.CommandType = CommandType.StoredProcedure;
                //cmd.Connection = sqlCon;
                cmd.Parameters.Clear();
                cmd.Parameters.Add(en.CreateParameter("@in_vchApplicationID", appId));
                cmd.Parameters.Add(en.CreateParameter("@in_vchSlipID", slipid));
                cmd.Parameters.Add(en.CreateParameter("@in_intWeightNumber", i + 1));

                cmd.Parameters.Add(en.CreateParameter("@in_fltGrossWeight", Convert.ToDouble(String.Format("{0:n0}", Convert.ToDouble(dgvWeight_Disp.Rows[i].Cells[1].Value)))));
                cmd.Parameters.Add(en.CreateParameter("@in_fltTareWeight", Convert.ToDouble(String.Format("{0:n0}", Convert.ToDouble(dgvWeight_Disp.Rows[i].Cells[2].Value)))));
                cmd.Parameters.Add(en.CreateParameter("@in_fltNetWeight", Convert.ToDouble(String.Format("{0:n0}", Convert.ToDouble(dgvWeight_Disp.Rows[i].Cells[3].Value)))));
                cmd.Parameters.Add(en.CreateParameter("@in_intPalletCount", Convert.ToDouble(String.Format("{0:n0}", Convert.ToDouble(dgvWeight_Disp.Rows[i].Cells[0].Value)))));
                cmd.Parameters.Add(en.CreateParameter("@in_vchDevice", GlobalVariable.Device));
                cmd.Parameters.Add(en.CreateParameter("@in_vchUserID", GlobalVariable.userName));

                DbDataAdapter da = en.CreateDataAdapter(cmd);
                dataset = new DataSet();
                da.Fill(dataset, "InsertWeightRecord");
                string status = dataset.Tables[0].Rows[0]["Status"].ToString();
                string errorCode = dataset.Tables[0].Rows[0]["ErrorCode"].ToString();
                string message = dataset.Tables[0].Rows[0]["Message"].ToString();

                if (status != "PASS")
                {
                    result = false;
                    CommonMessageBox.ShowMessageWarning(string.Format("{0}\r\n{1}\r\n[Insert Weight Record]", errorCode, message));
                    break;
                }
            }
            //}
            //catch (Exception objEx)
            //{
            //    CommonMessageBox.ShowMessageError(objEx);
            //}
            //finally
            //{
            //    if (sqlCon != null && sqlCon.State == ConnectionState.Open)
            //    {
            //        sqlCon.Close();
            //    }
            //}
            return result;
        }

        private bool InsertDimensionRecord(Entities en, DbTransaction tran)
        {
            bool result = true;
            //SqlCommand cmd = new SqlCommand();
            //try
            //{
            //    sqlCon.Open();
            DbCommand cmd = en.CreateCommand("usp_InsertDimensionRecord");
            cmd.CommandType = CommandType.StoredProcedure;
            //cmd.Transaction = tran;
            for (int i = 0; i < dgvDim.Rows.Count - 1; i++)
            {

                //cmd.CommandTimeout = 180;
                //cmd.CommandText = "usp_InsertDimensionRecord";

                //cmd.Connection = sqlCon;
                cmd.Parameters.Clear();
                cmd.Parameters.Add(en.CreateParameter("@in_vchApplicationID", appId));
                cmd.Parameters.Add(en.CreateParameter("@in_vchSlipID", slipid));
                cmd.Parameters.Add(en.CreateParameter("@in_intDimensionNumber", i + 1));
                cmd.Parameters.Add(en.CreateParameter("@in_fltLength", Convert.ToDouble(String.Format("{0:n0}", Convert.ToDouble(dgvDim.Rows[i].Cells[0].Value)))));
                cmd.Parameters.Add(en.CreateParameter("@in_fltWidth", Convert.ToDouble(String.Format("{0:n0}", Convert.ToDouble(dgvDim.Rows[i].Cells[1].Value)))));
                cmd.Parameters.Add(en.CreateParameter("@in_fltHeight", Convert.ToDouble(String.Format("{0:n0}", Convert.ToDouble(dgvDim.Rows[i].Cells[2].Value)))));
                cmd.Parameters.Add(en.CreateParameter("@in_intPieceCount", Convert.ToDouble(String.Format("{0:n0}", Convert.ToDouble(dgvDim.Rows[i].Cells[3].Value)))));
                cmd.Parameters.Add(en.CreateParameter("@in_vchDevice", GlobalVariable.Device));
                cmd.Parameters.Add(en.CreateParameter("@in_vchUserID", GlobalVariable.userName));
                DbDataAdapter da = en.CreateDataAdapter(cmd);

                dataset = new DataSet();
                
                da.Fill(dataset, "InsertDimensionRecord");
                string status = dataset.Tables[0].Rows[0]["Status"].ToString();
                string errorCode = dataset.Tables[0].Rows[0]["ErrorCode"].ToString();
                string message = dataset.Tables[0].Rows[0]["Message"].ToString();

                if (status != "PASS")
                {
                    result = false;
                    CommonMessageBox.ShowMessageWarning(string.Format("{0}\r\n{1}\r\n[Insert Dimension Record]", errorCode, message));
                    break;
                }
            }
            return result;
            //}
            //catch (Exception objEx)
            //{
            //    CommonMessageBox.ShowMessageError(objEx);
            //}
            //finally
            //{
            //    if (sqlCon != null && sqlCon.State == ConnectionState.Open)
            //    {
            //        sqlCon.Close();
            //    }
            //}
        }

        private bool InsertCommentRecord(Entities en, DbTransaction tran)
        {
            bool result = true;
            //SqlCommand cmd = new SqlCommand();
            //SqlDataAdapter da = null;
            //try
            //{
            //    sqlCon.Open();
            DbCommand cmd = en.CreateCommand("usp_InsertCommentRecord");
            cmd.CommandType = CommandType.StoredProcedure;
            //cmd.Transaction = tran;

            for (int i = 0; i < dgvOthInfo.Rows.Count - 1; i++)
            {
                //cmd.CommandTimeout = 180;
                //da = new SqlDataAdapter(cmd);
                //cmd.CommandText = "usp_InsertCommentRecord";

                //cmd.Connection = sqlCon;
                cmd.Parameters.Clear();
                cmd.Parameters.Add(en.CreateParameter("@in_vchApplicationID", appId));
                cmd.Parameters.Add(en.CreateParameter("@in_vchSlipID", slipid));
                cmd.Parameters.Add(en.CreateParameter("@in_vchCommentTypeID", GlobalVariable.commenttype_id[i].ToString()));
                cmd.Parameters.Add(en.CreateParameter("@in_intCommentNumber", i + 1));
                cmd.Parameters.Add(en.CreateParameter("@in_vchValue", dgvOthInfo.Rows[i].Cells[1].Value));
                cmd.Parameters.Add(en.CreateParameter("@in_vchDevice", GlobalVariable.Device));
                cmd.Parameters.Add(en.CreateParameter("@in_vchUserID", GlobalVariable.userName));
                DbDataAdapter da = en.CreateDataAdapter(cmd);

                dataset = new DataSet();
                da.Fill(dataset, "InsertCommentRecord");
                string status = dataset.Tables[0].Rows[0]["Status"].ToString();
                string errorCode = dataset.Tables[0].Rows[0]["ErrorCode"].ToString();
                string message = dataset.Tables[0].Rows[0]["Message"].ToString();

                if (status != "PASS")
                {
                    result = false;
                    CommonMessageBox.ShowMessageWarning(string.Format("{0}\r\n{1}\r\n[Insert Comment Record]", errorCode, message));
                    break;
                }

            }
            return result;
            //}
            //catch (Exception objEx)
            //{
            //    CommonMessageBox.ShowMessageError(objEx);
            //}
            //finally
            //{
            //    if (sqlCon != null && sqlCon.State == ConnectionState.Open)
            //    {
            //        sqlCon.Close();
            //    }
            //}
        }

        private void ReadOnly()
        {
            dgvWeight_Disp.ReadOnly = true;
            dgvWeight_Disp.Columns["Column7"].Visible = false;
            dgvWeight_Disp.Columns["Del"].Visible = true;
            btnAddWeight.Enabled = false;
            btnWeightClear.Enabled = false;
            dgvDim.ReadOnly = true;
            dgvDim.Columns["DimDel"].Visible = false;
            dgvDim.Columns["Column1"].Visible = true;
            btnDimClear.Enabled = false;
            dgvOthInfo.ReadOnly = true;
            dgvOthInfo.Columns["OtherDel"].Visible = false;
            dgvOthInfo.Columns["Column8"].Visible = true;
            btnAddOtherInfo.Enabled = false;
            btnOtherInfoClear.Enabled = false;
            btnPrint.Enabled = true;
            btnSave.Enabled = false;



        }

        private void ResetAll()
        {
            //dgvWeight_Disp.ReadOnly = false;
            dgvWeight_Disp.Columns["Column7"].Visible = true;
            dgvWeight_Disp.Columns["Del"].Visible = false;
            btnAddWeight.Enabled = true;
            btnMAWBSearch.Enabled = false;
            btnWeightClear.Enabled = true;
            dgvDim.ReadOnly = false;
            dgvDim.Columns["DimDel"].Visible = true;
            dgvDim.Columns["Column1"].Visible = false;
            btnDimClear.Enabled = true;
            //dgvOthInfo.ReadOnly = false;
            dgvOthInfo.Columns["OtherDel"].Visible = true;
            dgvOthInfo.Columns["Column8"].Visible = false;
            btnAddOtherInfo.Enabled = true;
            btnOtherInfoClear.Enabled = true;
            btnPrint.Enabled = false;
            btnSave.Enabled = true;
        }

        //kg


        //
        #endregion Save
        #region Private Method
        private void getMAWBConsol()
        {
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = null;
            try
            {
                string mawb = txtPrefix.Text + txtSerial.Text;
                //string prefix = mawb.Substring(0, 3);
                //string serial = mawb.Substring(3, 8);

                try
                {
                    sqlCon.Open();
                    cmd.CommandText = "usp_GetMAWB";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = sqlCon;
                    cmd.Parameters.AddWithValue("@in_vchApplicationID", appId);
                    cmd.Parameters.AddWithValue("@in_vchMAWB", mawb);
                    cmd.Parameters.AddWithValue("@in_vchMAWBPrefix", txtPrefix.Text);
                    cmd.Parameters.AddWithValue("@in_vchMAWBSerial", txtSerial.Text);
                    cmd.Parameters.AddWithValue("@in_vchHAWB", txtHAWB.Text);
                    cmd.Parameters.AddWithValue("@in_vchDevice", GlobalVariable.Device);
                    cmd.Parameters.AddWithValue("@in_vchUserID", GlobalVariable.userName);
                    cmd.CommandTimeout = 120;
                    da = new SqlDataAdapter(cmd);
                    dataset = new DataSet();
                    da.Fill(dataset, "testGetMAWB");
                    string status = dataset.Tables[0].Rows[0]["Status"].ToString();
                    string message = dataset.Tables[0].Rows[0]["Message"].ToString();

                    if (status == "PASS" && ValueTofrmAddMAWB.SelSource == "LOCAL")
                    {
                        //string hawb = "";
                        if (txtHAWB.Text == dataset.Tables[0].Rows[0]["hawb"].ToString())
                        {
                            E_ICS.frmMAWBsearch ms = new E_ICS.frmMAWBsearch(dataset, this);
                            if (ms.ShowDialog() == DialogResult.OK)
                            {
                                ResetAll();
                            }
                        }
                        else
                        {
                            //E_ICS.frmMAWBsearch ms = new E_ICS.frmMAWBsearch(dataset, this);
                            // ms.ShowDialog();
                            try
                            {
                                ValueTofrmAddMAWB.SelPrefix = txtPrefix.Text;
                                ValueTofrmAddMAWB.SelSerial = txtSerial.Text;
                                ValueTofrmAddMAWB.Selhawb = txtHAWB.Text;

                                E_ICS.frmAddMAWB am = new E_ICS.frmAddMAWB(this);
                                if (am.ShowDialog() == DialogResult.OK)
                                {
                                    ResetAll();
                                }
                            }
                            catch (Exception)
                            {

                                throw;
                            }
                        }
                    }
                    else
                    {
                        // CommonMessageBox.ShowMessageError(message);
                        try
                        {
                            ValueTofrmAddMAWB.SelPrefix = txtPrefix.Text;
                            ValueTofrmAddMAWB.SelSerial = txtSerial.Text;
                            ValueTofrmAddMAWB.Selhawb = txtHAWB.Text;

                            E_ICS.frmAddMAWB am = new E_ICS.frmAddMAWB(this);
                            if (am.ShowDialog() == DialogResult.OK)
                            {
                                ResetAll();
                            }
                        }
                        catch (Exception ex)
                        {

                            CommonMessageBox.ShowMessageError(ex);
                        }


                    }
                    sqlCon.Close();
                }
                catch (Exception objEx)
                {
                    CommonMessageBox.ShowMessageError(objEx);
                }
            }
            catch (Exception ex)
            {
                //string str = "You must enter 11 digits of MAWB";
                //MessageBox.Show(str);
                CommonMessageBox.ShowMessageError(ex);
            }
            finally
            {
                if (sqlCon != null && sqlCon.State != ConnectionState.Closed)
                {
                    sqlCon.Close();
                }
            }
        }
        private void getMAWBNonCon()
        {
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = null;
            try
            {
                string mawb = txtPrefix.Text + txtSerial.Text;
                //string prefix = mawb.Substring(0, 3);
                //string serial = mawb.Substring(3, 8);

                try
                {
                    sqlCon.Open();
                    cmd.CommandText = "usp_GetMAWB";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = sqlCon;
                    cmd.Parameters.AddWithValue("@in_vchApplicationID", appId);
                    cmd.Parameters.AddWithValue("@in_vchMAWB", mawb);
                    cmd.Parameters.AddWithValue("@in_vchMAWBPrefix", txtPrefix.Text);
                    cmd.Parameters.AddWithValue("@in_vchMAWBSerial", txtSerial.Text);
                    cmd.Parameters.AddWithValue("@in_vchHAWB", txtHAWB.Text);
                    cmd.Parameters.AddWithValue("@in_vchDevice", GlobalVariable.Device);
                    cmd.Parameters.AddWithValue("@in_vchUserID", GlobalVariable.userName);
                    cmd.CommandTimeout = 120;
                    da = new SqlDataAdapter(cmd);
                    dataset = new DataSet();
                    da.Fill(dataset, "testGetMAWB");
                    string status = dataset.Tables[0].Rows[0]["Status"].ToString();
                    if (status == "PASS" && ValueTofrmAddMAWB.SelSource == "LOCAL")
                    {
                        E_ICS.frmMAWBsearch ms = new E_ICS.frmMAWBsearch(dataset, this);
                        ///ms.ShowDialog();
                        if (ms.ShowDialog() == DialogResult.OK)
                        {
                            ResetAll();
                        }

                    }
                    else
                    {
                        // CommonMessageBox.ShowMessageError(message);
                        try
                        {
                            ValueTofrmAddMAWB.SelPrefix = txtPrefix.Text;
                            ValueTofrmAddMAWB.SelSerial = txtSerial.Text;
                            ValueTofrmAddMAWB.Selhawb = txtHAWB.Text;

                            E_ICS.frmAddMAWB am = new E_ICS.frmAddMAWB(this);
                            if (am.ShowDialog() == DialogResult.OK)
                            {
                                ResetAll();
                            }
                        }
                        catch (Exception ex)
                        {

                            CommonMessageBox.ShowMessageError(ex);
                        }


                    }
                    sqlCon.Close();
                }
                catch (Exception objEx)
                {
                    CommonMessageBox.ShowMessageError(objEx);
                }
            }
            catch (Exception ex)
            {
                //string str = "You must enter 11 digits of MAWB";
                //MessageBox.Show(str);
                CommonMessageBox.ShowMessageError(ex);
            }
            finally
            {
                if (sqlCon != null && sqlCon.State != ConnectionState.Closed)
                {
                    sqlCon.Close();
                }
            }
        }
        private void clearAll()
        {
            txtPrefix.Text = String.Empty;
            txtSerial.Text = String.Empty;
            txtHAWB.Text = String.Empty;
            radioButton1.Checked = false;
            radioButton2.Checked = false;
            checkBox1.Checked = false;
            txtSeq.Text = String.Empty;
            txtFltNo.Text = String.Empty;
            txtFltDate.Text = String.Empty;
            txtDest.Text = String.Empty;
            txtAgentCode.Text = String.Empty;
            txtAgentName.Text = String.Empty;
            txtNatureGood.Text = String.Empty;
            txtPieces.Text = String.Empty;
            txtSlipNO.Text = String.Empty;
            dgvWeight_Disp.Rows.Clear();
            clearTextBox();
            dgvDim.Rows.Clear();
            dgvOthInfo.Rows.Clear();
            lblTotal.Text = "0";
            E_ICS.frmMAWBsearch ms = new E_ICS.frmMAWBsearch(dataset, this);
            ms.ClearValueToAddMAWB();

        }
        private void clearTextBox()
        {
            txtTotalGross.Text = "0";
            sumG = 0;
            sumN = 0;
            sumT = 0;
            sumP = 0;
            sumPiecs = 0;
            txtTotalTare.Text = "0";
            txtTotalNet.Text = "0";
            txtTotalPallet.Text = "0";
            txtWeighing.Text = "0";

        }

        private void setWeighing(DataGridView a)
        {
            foreach (DataGridViewRow row in a.Rows)
            {
                if (row.Index == a.Rows.Count - 1)
                {
                    // txtWeighing.Text = "0";
                }
                else
                {
                    //row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
                    weighting = row.Index + 1;
                    txtWeighing.Text = weighting.ToString();
                }
            }
        }
        #endregion
        private bool checkStation()
        {
            bool result = false;
            EicsSetupComponent comp = new EicsSetupComponent();
            EicsSetup param = new EicsSetup();
            param.Device = GlobalVariable.user.Device;
            param.AppId = GlobalVariable.user.ApplicationID;
            param.UserId = GlobalVariable.user.UserID;
            List<ObjectContext> items = comp.Search(param);
            if (items != null && items.Count > 0)
            {
                foreach (ObjectContext item in items)
                {
                    if (((EicsSetup)item).StationId == GlobalVariable.user.Device)
                    {
                        result = true;
                        break;
                    }
                    else
                    {
                        result = false;
                        CommonMessageBox.ShowMessageWarning("There isn't this staion in staion setup!");
                        break;
                    }
                }
            }
            return result;
        }
        private void getShipmentType()
        {
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = null;
            try
            {
                string mawb = txtPrefix.Text + txtSerial.Text;
                //string prefix = mawb.Substring(0, 3);
                //string serial = mawb.Substring(3, 8);

                try
                {
                    sqlCon.Open();
                    cmd.CommandText = "usp_GetMAWB";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = sqlCon;
                    cmd.Parameters.AddWithValue("@in_vchApplicationID", appId);
                    cmd.Parameters.AddWithValue("@in_vchMAWB", mawb);
                    cmd.Parameters.AddWithValue("@in_vchMAWBPrefix", txtPrefix.Text);
                    cmd.Parameters.AddWithValue("@in_vchMAWBSerial", txtSerial.Text);

                    cmd.Parameters.AddWithValue("@in_vchDevice", GlobalVariable.Device);
                    cmd.Parameters.AddWithValue("@in_vchUserID", GlobalVariable.userName);
                    cmd.CommandTimeout = 120;
                    da = new SqlDataAdapter(cmd);
                    dataset = new DataSet();
                    da.Fill(dataset, "testGetMAWB");
                    string status = dataset.Tables[0].Rows[0]["Status"].ToString();
                    string msg = dataset.Tables[0].Rows[0]["Message"].ToString();
                    if (status == "PASS")
                    {
                        ValueTofrmAddMAWB.Selshipment_type = dataset.Tables[0].Rows[0]["shipment_type"].ToString();
                        ValueTofrmAddMAWB.SelSource = dataset.Tables[0].Rows[0]["source"].ToString();
                    }
                    else
                    {
                        // CommonMessageBox.ShowMessageError(message);
                        try
                        {
                            //ValueTofrmAddMAWB.SelPrefix = txtPrefix.Text;
                            //ValueTofrmAddMAWB.SelSerial = txtSerial.Text;
                            //ValueTofrmAddMAWB.Selhawb = txtHAWB.Text;

                            //E_ICS.frmAddMAWB am = new E_ICS.frmAddMAWB(this);
                            //am.ShowDialog();
                        }
                        catch (Exception ex)
                        {

                            //CommonMessageBox.ShowMessageError(ex);
                        }


                    }
                    sqlCon.Close();
                }
                catch (Exception objEx)
                {
                    CommonMessageBox.ShowMessageError(objEx);
                }
            }
            catch (Exception ex)
            {
                //string str = "You must enter 11 digits of MAWB";
                //MessageBox.Show(str);
                CommonMessageBox.ShowMessageError(ex);
            }
            finally
            {
                if (sqlCon != null && sqlCon.State != ConnectionState.Closed)
                {
                    sqlCon.Close();
                }
            }
        }

        private void txtHAWB_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (!(Regex.IsMatch(e.KeyChar.ToString(), reg)))//|| (e.KeyChar == (char)Keys.Back)))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void dgvDim_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }


    }
}
